package com.bawei.day15_service2;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import androidx.annotation.Nullable;

public class MyItentService extends IntentService {
    public MyItentService() {
        super("MyItentService");
    }
    //内部有一个工作线程，执行耗时操作
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            URL url = new URL("http://39.98.153.96:8080/api/Test/GetTestAlbums");
            HttpURLConnection httpURLConnection  = (HttpURLConnection) url.openConnection();
            httpURLConnection.setReadTimeout(6000);
            httpURLConnection.setConnectTimeout(6000);
            httpURLConnection.connect();
            InputStream inputStream = httpURLConnection.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes))!=-1){
                stringBuffer.append(new String(bytes,0,len));
            }
            //使用广播返回数据給activity
            Intent intent1 = new Intent();
            intent1.setAction("com.bawei.net");
            Bundle bundle = new Bundle();
            bundle.putString("result",stringBuffer.toString());
            intent1.putExtras(bundle);
            sendBroadcast(intent1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("ytx", "onCreate: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("ytx", "onDestroy: ");
    }
}
